package com.ruoyi.order.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.order.api.domain.Order;
import com.ruoyi.order.domain.OrderService;
import com.ruoyi.order.mapper.OrderMapper;
import com.ruoyi.order.mapper.OrderServiceMapper;
import com.ruoyi.order.service.IOrderService;
import com.ruoyi.service.api.RemoteServiceService;
import com.ruoyi.service.api.domain.CheService;
import com.ruoyi.shop.api.RemoteCouponService;
import com.ruoyi.shop.api.RemoteShopService;
import com.ruoyi.shop.api.domain.CheCoupon;
import com.ruoyi.shop.api.domain.CheShop;
import com.ruoyi.system.api.RemoteUserrService;
import com.ruoyi.system.api.domain.CheUserr;
import com.ruoyi.user.api.RemoteCarService;
import com.ruoyi.user.api.domain.CheCar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * 订单Service业务层处理
 *
 * @author yun
 * @date 2024-12-31
 */
@Service
public class OrderServiceImpl implements IOrderService
{
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderServiceMapper orderServiceMapper;

    @Autowired
    private RemoteCarService remoteCarService;
    @Autowired
    private RemoteUserrService remoteUserService;
    @Autowired
    private RemoteShopService remoteShopService;
    @Autowired
    private RemoteServiceService remoteServiceService;
    @Autowired
    private RemoteCouponService remoteCouponService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public Order selectOrderById(Long id)
    {
        Order order = orderMapper.selectOrderById(id);
        if(order == null){
            return null;
        }
        if(order.getHasCar() && order.getCarId()!= null){
            setCar(order);
        }
        if(order.getHasUser() && order.getUserId() != null){
            setUserr(order);
        }
        if(order.getHasShop() && order.getShopId() != null){
            setShop(order);
        }
        if(order.getHasCoupon() && order.getCouponId() != null){
            setCoupon(order);
        }
        if(order.getHasService()){
            setService(order);
        }

        return order;
    }

    /**
     * 查询订单列表
     *
     * @param order 订单
     * @return 订单
     */
    @Override
    public List<Order> selectOrderList(Order order)
    {
        List<Order> list = orderMapper.selectOrderList(order);
        list.forEach(item->{
            if(item != null){
                if(order.getHasCar() && item.getCarId()!= null){
                    setCar(item);
                }
                if(order.getHasUser() && item.getUserId()!= null){
                    setUserr(item);
                }
                if(order.getHasShop() && item.getShopId()!= null){
                    setShop(item);
                }
                if(order.getHasCoupon() && item.getCouponId() != null){
                    setCoupon(item);
                }
                if(order.getHasService()){
                    setService(item);
                }
            }
        });
        return list;
    }

    @Override
    public List<Order> selectOrderListByIds(Long[] ids) {
        if(ids == null || ids.length == 0)
            return  null;
        List<Order> list = orderMapper.selectOrderListByIds(ids);

        return list;
    }

    /**
     * 新增订单
     *
     * @param order 订单
     * @return 结果
     */
    @Transactional
    @Override
    public long insertOrder(Order order)
    {
//        添加核销码
        order.setVerificationCode(UUID.randomUUID().toString().replace("-", "").substring(0,5));
//        添加订单编号
        order.setNumber(UUID.randomUUID().toString().replace("-", "").substring(0,12));

        order.setCreateTime(DateUtils.getNowDate());

        int i = orderMapper.insertOrder(order);

//        添加子表信息（订单服务表）
        addOrderService(order);

        return order.getId() != null ? order.getId() : 0;
    }

    /**
     * 修改订单
     *
     * @param order 订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateOrder(Order order)
    {
        if(order.getIsServiceChanged()){
            addOrderService(order);
        }
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOrderByIds(Long[] ids)
    {
        for (Long id : ids) {
            orderServiceMapper.deleteByOrderId(id);
        }
        return orderMapper.deleteOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOrderById(Long id)
    {
        orderServiceMapper.deleteByOrderId(id);
        return orderMapper.deleteOrderById(id);
    }


    //    添加车辆信息
    private void setCar(Order order){
        AjaxResult info = remoteCarService.getInfo(order.getCarId(), null);
        Object o = info.get(AjaxResult.DATA_TAG);
//            System.out.println("order.carId:"+order.getCarId()+":"+info);
//            System.out.println("data:"+o);
        if(o == null){
            return;
        }
        CheCar car = JSON.parseObject(JSON.toJSON(o).toString(), CheCar.class);
        if(car != null){
            order.setCar(car);
        }
    }
//    添加用户信息
    private void setUserr(Order order){
        AjaxResult info = remoteUserService.getInfo(order.getUserId(), null);
        Object o = info.get(AjaxResult.DATA_TAG);
//        System.out.println("data:"+o);
        if(o == null){
            return;
        }
        CheUserr user = JSON.parseObject(JSON.toJSON(o).toString(), CheUserr.class);
        if(user != null){
            order.setUser(user);
        }

    }

//    添加商户
    private void setShop(Order order){
        AjaxResult info = remoteShopService.getInfo(order.getShopId(), null);
        Object o = info.get(AjaxResult.DATA_TAG);
//        System.out.println("data:"+o);
        if(o == null){
            return;
        }
        CheShop user = JSON.parseObject(JSON.toJSON(o).toString(), CheShop.class);
        if(user != null){
            order.setShop(user);
        }
    }

//    添加优惠卷信息
    private void setCoupon(Order order){
        AjaxResult info = remoteCouponService.getInfo(order.getCouponId(), null);
        if(info == null){
            return;
        }
        Object o = info.get(AjaxResult.DATA_TAG);
        if(o == null){
            return;
        }
        CheCoupon cheCoupon = JSON.parseObject(JSON.toJSON(o).toString(), CheCoupon.class);
        if(cheCoupon != null){
            order.setCoupon(cheCoupon);
        }

    }

    //    添加服务项目
    private void setService(Order order){
        if(order.getId() == null)
            return;

//        根据订单id获取服务项目id列表
        List<Long> list = orderServiceMapper.selectIdsByOrderId(order.getId());
        if(list == null || list.isEmpty()){
            return;
        }
        order.setServiceIds(list);
        Long[] ids = list.toArray(new Long[list.size()]);

//        调用远程接口获取
        AjaxResult info = remoteServiceService.getInfo(ids, null);
//        判断数据是否存在
        Object o = info.get(AjaxResult.DATA_TAG);
        if(o == null){
            return;
        }
//        System.out.println("data(service):"+o);

//        获取服务列表
        List<CheService> cheServices = JSON.parseArray(JSON.toJSON(o).toString(), CheService.class);
//        System.out.println(cheServices);
        if(cheServices != null){
            order.setServiceList(cheServices);
        }

    }

//    添加子表信息（订单服务）
    private void addOrderService(Order order){
        if(order.getIsServiceChanged()){
//            修改
//            删除订单服务信息
            orderServiceMapper.deleteByOrderId(order.getId());
        }


        if(order.getServiceIds() == null || order.getServiceIds().isEmpty()){
            return;
        }
        List<Long> ids = order.getServiceIds();
        OrderService orderService = new OrderService();
        orderService.setOrderId(order.getId());
        ids.forEach(item->{
            orderService.setServiceId(item);
            orderServiceMapper.insertOrderService(orderService);
        });
    }

}
